package demo1;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

public class WindowGuess extends JFrame implements ActionListener {
    int number ;
    int count ;
    JLabel hintLabel ;
    JTextField inputGuess ;
    JButton buttonGetNumber , buttonEnter ;
    public WindowGuess(){
        number = new Random().nextInt(100)+1 ;
        setLayout(new FlowLayout());
        buttonGetNumber = new JButton("得到一个1到100的随机数");
         add(buttonGetNumber);
         this.hintLabel = new JLabel("输入你的猜测:",JLabel.CENTER);
         this.hintLabel.setBackground(Color.cyan);
         this.inputGuess = new JTextField(10);
         add(this.hintLabel);
         add(this.inputGuess);
         this.buttonEnter = new JButton("确定");
         add(this.buttonEnter);
         this.buttonEnter.addActionListener(this);
         this.buttonGetNumber.addActionListener((e) -> {
             number = new Random().nextInt(100)+1 ;
             count = 0 ;
             hintLabel.setText("输入你的猜测");
             inputGuess.setText(null);
             buttonEnter.setEnabled(true);
         });
         Font font = new Font("宋体",Font.PLAIN,30);
         SetFont.setFont(font , hintLabel , buttonEnter , buttonGetNumber,  inputGuess);
         setBounds(100 , 100 , 150 , 150 );
         setVisible(true);
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         validate();

    }

    @Override
    public void actionPerformed(ActionEvent e) {
       buttonGetNumber.setEnabled(false);
       int guess = 0 ;
       try{
           guess = Integer.parseInt(inputGuess.getText());
           count++ ;
           if(guess == number){
               hintLabel.setText("猜对了(猜测次数:"+ count+")");
               buttonEnter.setEnabled(false);
               buttonGetNumber.setEnabled(true);
           }else if(guess > number){
               hintLabel.setText("猜大了(猜测次数:"+ count+")");
               inputGuess.setText(null);
           }else if(guess < number){
               hintLabel.setText("猜小了(猜测次数:"+ count+")");
               inputGuess.setText(null);
           }
       }catch (NumberFormatException event){
           hintLabel.setText("请输入你猜的数字");

       }

    }
}
